package com.hanbang.chu_xing_gao_zhao.view_find_classroom;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hanbang.chu_xing_gao_zhao.application.HttpInterfaces;
import com.hanbang.chu_xing_gao_zhao.application.MyApplication;
import com.hanbang.chu_xing_gao_zhao.base.BaseDataActivity;
import com.hanbang.chu_xing_gao_zhao.myview.GridViewForScrollView;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic;
import com.hanbang.chu_xing_gao_zhao.myview.MorePopupWindowPublic_B;
import com.hanbang.chu_xing_gao_zhao.myview.MyDialog;
import com.hanbang.chu_xing_gao_zhao.utils.MyLog;
import com.hanbang.chu_xing_gao_zhao.utils.MyRequestCallBack;
import com.hanbang.chu_xing_gao_zhao.utils.MySharedPreferences;
import com.hanbang.chu_xing_gao_zhao.utils.MyToast;
import com.hanbang.chu_xing_gao_zhao.utils.StringUtils_2;
import com.hanbang.chu_xing_gao_zhao.utils.SystemTools;
import com.hanbang.chu_xing_gao_zhao.utils.UiUtils;
import com.hanbang.cxgz_2.R;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.client.HttpRequest;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 资料上传页面
 */
public class FindClassroomDataUploadingActivity extends BaseDataActivity {

    /**
     * 资料类型-数据
     */
    private int dataType = 0;
    /**
     * 图片,视频,文件，路径
     */
    private String path = "";
    /**
     * 图片路径集合
     */
    private ArrayList<String> picturePathData;
    /**
     * 图片适配器
     */
    private PictureShowAdapter adapter;
    /**
     * 图片显示
     */
    private GridViewForScrollView pictureShowGridview;

    /**
     * 过程——图片显示
     */
    private GridViewForScrollView processPictureGridview;
    /**
     * 过程——图片适配器
     */
    private PictureShowAdapter processAdapter;
    /**
     * 过程——图片路径集合
     */
    private ArrayList<String> processPicturePathData;
    /**
     * 图片,视频,文件，路径
     */
    private String processPath = "";

    /**
     * 标题图片路径
     */
    private String pathPicture = "";
    /**
     * 费用模试
     * 免费的为0
     */
    private int modelCost = 0;

    /**
     * 选择图片
     */
    private LinearLayout selectPicture;
    /**
     * 选择更多
     */
    private LinearLayout selectMore;
    /**
     * 资料名称
     */
    private EditText dataName;
    /**
     * 资料简介
     */
    private EditText dataBrief;
    /**
     * 免费
     */
    private TextView free;
    /**
     * 收费
     */
    private TextView charge;
    /**
     * 价格
     */
    private EditText price;
    /**
     * 上传
     */
    private TextView uploading;
    /**
     * 图片显示
     */
    private ImageView showPicture;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_classroom_data_uploading);
        initView();

        setOnClickListener();
    }

    /**
     * 初始化view
     */
    private void initView() {
        setTitleMore(View.VISIBLE, View.INVISIBLE, "上传资料", null, null, null);
        setBackArrows(findViewById(R.id.bar_top_conver_classify_back));

        selectPicture = (LinearLayout) findViewById(R.id.ll_find_classroom_ata_uploading_addPicture);
        selectMore = (LinearLayout) findViewById(R.id.ll_find_classroom_daata_uploading_selectModel);
        dataName = (EditText) findViewById(R.id.et_find_classroom_data_uploading_classroomName);
        dataBrief = (EditText) findViewById(R.id.et_find_classroom_data_uploading_classroomBrief);
        free = (TextView) findViewById(R.id.tv_find_classroom_data_uploading_free);
        charge = (TextView) findViewById(R.id.tv_find_classroom_data_uploading_charge);
        price = (EditText) findViewById(R.id.et_find_classroom_data_uploading_price);
        uploading = (TextView) findViewById(R.id.tv_find_classroom_data_uploading_uploading);
        showPicture = (ImageView) findViewById(R.id.iv_find_classroom_data_uploading_showPicture);


        //添加图片与视频初始化
        pictureShowGridview = (GridViewForScrollView) findViewById(R.id.gv_find_classroom_data_uploading_pictureShow);
        picturePathData = new ArrayList<String>();
        adapter = new PictureShowAdapter(picturePathData, 1);
        pictureShowGridview.setAdapter(adapter);

        //添加过程图片
        processPictureGridview = (GridViewForScrollView) findViewById(R.id.gv_find_classroom_data_uploading_pictureProcess);
        processPicturePathData = new ArrayList<String>();
        processAdapter = new PictureShowAdapter(processPicturePathData, 2);
        processPictureGridview.setAdapter(processAdapter);


    }

    /**
     * 设置点击事件
     */
    private void setOnClickListener() {
        selectPicture.setOnClickListener(onClickListener);
        selectMore.setOnClickListener(onClickListener);
        free.setOnClickListener(onClickListener);
        charge.setOnClickListener(onClickListener);
        uploading.setOnClickListener(onClickListener);

    }


    /**
     * 处理监听
     */
    @SuppressWarnings("unused")
    private OnClickListener onClickListener = new OnClickListener() {
        MorePopupWindowPublic_B hottestPopup;

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                //选择免费
                case R.id.tv_find_classroom_data_uploading_free:
                    modelCost = 0;
                    free.setBackgroundResource(R.drawable.bg_corners12__yellow_background);
                    charge.setBackgroundResource(R.drawable.bg_corners12_graydd_background);
                    price.setFocusable(false);
                    price.setFocusableInTouchMode(false);
                    price.setText("");
                    break;
                //选择收费
                case R.id.tv_find_classroom_data_uploading_charge:
                    modelCost = 1;
                    free.setBackgroundResource(R.drawable.bg_corners12_graydd_background);
                    charge.setBackgroundResource(R.drawable.bg_corners12__yellow_background);
                    price.setFocusable(true);
                    price.setFocusableInTouchMode(true);
                    break;


                case R.id.ll_find_classroom_daata_uploading_selectModel:
                    hottestPopup = new MorePopupWindowPublic_B(FindClassroomDataUploadingActivity.this, dataTypes, 8, 100);

                    hottestPopup.showPopupWindow(selectMore.getChildAt(0), 2);

                    break;
                //选择相片
                case R.id.ll_find_classroom_ata_uploading_addPicture:
                    // 新建一个dialog 对话框
                    MyDialog myDialog = new MyDialog(FindClassroomDataUploadingActivity.this, R.style.about_me_dialog, MyDialog.MODE.HEAD);
                    // 添加图片的监听
                    myDialog.setOnClickCallback(new com.hanbang.chu_xing_gao_zhao.myview.MyDialog.OnClickCallback() {

                        @Override
                        public void onClick(MyDialog dialog, Object number, Object content) {

                            // 拍照
                            if ((Integer) number == 1) {
                                pathPicture = "";
                                File fDir = new File(MyApplication.picFilepath);
                                pathPicture = System.currentTimeMillis() + ".jpg";
                                if (fDir.exists() || fDir.mkdirs()) {
                                    File cameraFile = new File(fDir, pathPicture);
                                    if (!cameraFile.exists()) {
                                        try {
                                            cameraFile.createNewFile();
                                        } catch (IOException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(cameraFile));
                                    startActivityForResult(intent, 887);
                                }
                                // 相册选择
                            } else if ((Integer) number == 2) {
                                // 获取相册
                                Intent intent = new Intent();
                                intent.setType("image/*");

                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 888);
                            }

                        }
                    });
                    myDialog.show();

                    break;


                case R.id.tv_find_classroom_data_uploading_uploading:
                    if (pathPicture.equals("")) {
                        MyToast.show(FindClassroomDataUploadingActivity.this, "标题图片不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (((TextView) findViewById(R.id.tv_find_classroom_data_uploading_dataType)).getText().toString().equals("请选择")) {
                        MyToast.show(FindClassroomDataUploadingActivity.this, "资料类型没有选择", Toast.LENGTH_SHORT);
                        return;
                    }
                    if (dataName.getText().toString().equals("")) {
                        MyToast.show(FindClassroomDataUploadingActivity.this, "标题不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (dataBrief.getText().toString().equals("")) {
                        MyToast.show(FindClassroomDataUploadingActivity.this, "课堂简介不能为空", Toast.LENGTH_SHORT);
                        return;
                    }

                    if (picturePathData.size() == 0) {
                        MyToast.show(FindClassroomDataUploadingActivity.this, "资料文件不能为空", Toast.LENGTH_SHORT);
                        return;
                    }


                    if (modelCost == 1 && price.getText().toString().equals("")) {
                        MyToast.show(FindClassroomDataUploadingActivity.this, "收费模式价格不能为空", Toast.LENGTH_SHORT);
                        return;
                    }
                    httpClassroomApply();
                    break;

                default:
                    break;
            }


            // 最热点击监听的处理
            if (hottestPopup != null) {


                hottestPopup.setOnClickCallback(new MorePopupWindowPublic_B.OnClickCallback() {

                    @Override
                    public void onClick(MorePopupWindowPublic_B morePopWindow, int number, String content, int type) {

                        if (type == 100) {
                            dataType = number;

                            ((TextView) findViewById(R.id.tv_find_classroom_data_uploading_dataType)).setText(content);
                        }


                    }
                });
            }


        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        /**
         * 获取图片地址
         */
        if (requestCode == 888 && resultCode == -1) {
            Uri uri = data.getData();
            pathPicture = SystemTools.getPath(FindClassroomDataUploadingActivity.this, uri);
            bitmapUtils.display(showPicture, pathPicture);
            selectPicture.setVisibility(View.GONE);
            // 获取拍照的图片路径
        } else if (requestCode == 887 && resultCode == -1) {
            File fDir = new File(MyApplication.picFilepath);
            // 判断文件夹是否存在
            if (fDir.exists() || fDir.mkdirs()) {
                File cameraFile = new File(fDir, pathPicture);
                // 判断文件时是否存在
                if (cameraFile.exists()) {
                    pathPicture = cameraFile.getPath();
                    bitmapUtils.display(showPicture, pathPicture);
                    selectPicture.setVisibility(View.GONE);
                } else {
                    MyToast.show(FindClassroomDataUploadingActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
                }
            } else {
                MyToast.show(FindClassroomDataUploadingActivity.this, "获取照片失败！", Toast.LENGTH_SHORT);
            }
        }


        /**
         * 获取图片,视频,文件地址
         */
        if (requestCode == 999 && resultCode == -1) {
            Uri uri = data.getData();
            path = SystemTools.getPath(FindClassroomDataUploadingActivity.this, uri);
            picturePathData.add(path);
            adapter.notifyDataSetChanged();
            MyLog.i("text", "*111**" + path);// *****
        }


        /**
         * 过程图片
         */
        if (requestCode == 800 && resultCode == -1) {
            Uri uri = data.getData();
            processPath = SystemTools.getPath(FindClassroomDataUploadingActivity.this, uri);
            processPicturePathData.add(processPath);
            processAdapter.notifyDataSetChanged();
        }
    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
    }


    /**
     * gridview adapter
     *
     * @author Administrator
     */
    class PictureShowAdapter extends BaseAdapter {
        public ArrayList<String> list;
        /**
         * 1表示添加图片，视频，文件
         * 2表示添加过程图片
         */
        private int type;

        public PictureShowAdapter(ArrayList<String> list, int type) {

            if (list != null) {
                this.list = list;
                this.type = type;


            } else {
                list = new ArrayList<String>();

            }
        }

        @Override
        public int getCount() {
            return list.size() + 1;
        }

        @Override
        public String getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {

            UiUtils.applyFont(convertView);
            ViewHolder viewHolder;
            if (convertView == null) {// 是空加载
                convertView = getLayoutInflater().inflate(R.layout.item_dycamic_horizontal_listview_delect, null);
                viewHolder = new ViewHolder();
                viewHolder.picture = (ImageView) convertView.findViewById(R.id.iv_item_shoppingcart_recommend_image);
                viewHolder.deletePicture = (ImageView) convertView
                        .findViewById(R.id.iv_item_shoppingcart_recommend_delete);
                convertView.setTag(viewHolder);
            } else {// 不是空复用

                viewHolder = (ViewHolder) convertView.getTag();
            }

            // 添加加号
            if (position == list.size()) {
                viewHolder.picture.setPadding(10, 70, +70 + 60, 70);
                viewHolder.picture.setImageResource(R.drawable.add);
                viewHolder.deletePicture.setVisibility(View.GONE);
                // 添加图片
            } else {
                viewHolder.picture.setPadding(0, 0, 0, 00);
                viewHolder.deletePicture.setVisibility(View.VISIBLE);
                //如果是视频则显示一个播放按钮
                if (StringUtils_2.getText(list.get(position), ".").equals("mp4")) {
                    viewHolder.picture.setImageResource(R.drawable.play);

                    //如果是图片格式显示原图
                } else if (StringUtils_2.getText(list.get(position), ".").equals("jpg") || (StringUtils_2.getText(list.get(position), ".").equals("pag"))) {
                    bitmapUtils.display(viewHolder.picture, list.get(position));
                    //如果是文件显示一张文件默认图片
                } else {
                    viewHolder.picture.setImageResource(R.drawable.file_icon);
                }


            }

            if (type == 1) {
                viewHolder.picture.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 获取相册
                        Intent intent = new Intent();
                        intent.setType("image/*;video/*;file/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, 999);
                    }
                });
            }

            if (type == 2) {
                viewHolder.picture.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // 获取相册
                        Intent intent = new Intent();
                        intent.setType("image/*");
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        intent.addCategory(Intent.CATEGORY_OPENABLE);
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, 800);
                    }
                });
            }


            // 删除图片
            viewHolder.deletePicture.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    if (type == 1) {
                        picturePathData.remove(position);
                        adapter.notifyDataSetChanged();
                    } else {
                        processPicturePathData.remove(position);
                        processAdapter.notifyDataSetChanged();
                    }

                }
            });

            return convertView;
        }

        class ViewHolder {// 进行缓存保存
            private ImageView picture; // 图片
            private ImageView deletePicture; // 删除 图片

        }

    }


    /**
     * 添加学习资料
     * <p/>
     * category_id：类别，备注，这个效果图上没有体现出来
     * price：价格，免费的为0
     * remark：简介
     * title：标题
     * img_url：主图
     * file_url:资料
     * imgs_url:资料截图
     */
    private void httpClassroomApply() {

        RequestParams params = new RequestParams();
        params.addBodyParameter("telphone", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindClassroomDataUploadingActivity.this, MySharedPreferences.USER_DATA, "tlephone"));
        params.addBodyParameter("password", MySharedPreferences.getSharedPreferencesKeyAndValue(
                FindClassroomDataUploadingActivity.this, MySharedPreferences.USER_DATA, "password"));

        params.addBodyParameter("category_id", dataType + "");

        params.addBodyParameter("price", price.getText().toString());
        params.addBodyParameter("remark", dataBrief.getText().toString());
        params.addBodyParameter("title", dataName.getText().toString());

        //主图片``
        File f = new File(pathPicture);
        params.addBodyParameter("img_url", f);

        //多个图片与视频
        for (int i = 0; i < picturePathData.size(); i++) {

            File picture = new File(picturePathData.get(i));

            if (picture.exists()) {
                params.addBodyParameter("file_url", picture);
            }
        }

        //多个图片与视频
        for (int i = 0; i < processPicturePathData.size(); i++) {

            File picture = new File(processPicturePathData.get(i));

            if (picture.exists()) {

                params.addBodyParameter("imgs_url", picture);

            }
        }


        httpUtils.send(HttpRequest.HttpMethod.POST, HttpInterfaces.xuexiziliao_Add, params,

                new MyRequestCallBack<String>(this, "正在申请上传...") {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        super.onSuccess(responseInfo);

                        try {
                            JSONObject json = new JSONObject(responseInfo.result);
                            int statrs = json.getInt("Result");
                            String msg = json.getString("Msg");
                            if (statrs == 0) {
                                MyToast.show(FindClassroomDataUploadingActivity.this, "申请成功", Toast.LENGTH_LONG);
                                finish();
                            } else {
                                MyToast.show(FindClassroomDataUploadingActivity.this, msg, Toast.LENGTH_LONG);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            MyToast.show(FindClassroomDataUploadingActivity.this, "服务器忙请稍后重试...", Toast.LENGTH_LONG);
                        }
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        super.onLoading(total, current, isUploading);


                    }
                });

    }


}
